const MAX_IMAGE_SIZE = 1
const MAX_IMAGE_SIZE_BYTES = MAX_IMAGE_SIZE * 1024 * 1024

export default {
  props: {
    action: {
      type: String,
      required: true
    },
    tokenService: {
      type: Function,
      required: true
    },
    tokenParam: {
      type: Object,
      default() {
        return {}
      }
    },
    hasToken: {
      type: Boolean,
      default() {
        return true
      }
    },
    value: {
      type: Array,
      default() {
        return []
      }
    },
    disabled: Boolean,
    max: {
      type: Number,
      default: Infinity
    },
    picType: String,
    marginRight: String
  },
  data() {
    return {
      data: {
        behavior: 'uploadImage'
      },
      inputName: 'file',
      imageList: [],
      isShowPreview: false,
      previewImage: '',
      isUploading: false,
      progress: 0,
      randomKey: Math.round(Math.random() * 1000000),
      uploadLoading: false,
      token: ''
    }
  },
  async created() {
    this.initList()
  },
  watch: {
    value(value) {
      this.initList()
    }
  },
  methods: {
    initList() {
      this.imageList = _.clone(this.value)
    },

    // emit
    emit(list = this.imageList) {
      this.$emit('input', list)
    },

    // 上传前钩子
    handleBeforeUpload(file) {
      this.uploadLoading = true
      return new Promise(async (res, rej) => {
        try {
          // const isRightType = this.picType.includes(file.type)
          const isLtM = file.size / MAX_IMAGE_SIZE_BYTES
          // if (!isRightType) {
          //   this.uploadLoading = false
          //   Tip.error(`图片只能是 ${this.picType} 格式`)
          // }
          if (!isLtM) {
            this.uploadLoading = false
            Tip.error(`图片大小不能超过 ${MAX_IMAGE_SIZE}MB`)
          }
          if (isLtM) {
            if (!this.hasToken) {
              this.progress = 0
              res()
              return
            }
            let data = await this.tokenService({
              ...this.tokenParam,
              fileName: file.name
            })
            this.token = data.token
            this.$emit('getToken', data.token)
            this.progress = 0
            res()
          } else {
            this.uploadLoading = false
            rej()
          }
        } catch (error) {
          console.log(error)
          this.uploadLoading = false
          rej()
        }
      })
    },

    //生成预览图
    reads(file) {
      var _this = this //定义一个文件阅读器
      var reader = new FileReader() //文件装载后将其显示在图片预览里
      reader.onload = function(e) {
        _this.imageList.push(reader.result) //将bade64位图片保存至数组里供上面图片显示
        _this.emit(_this.imageList)
      }
      reader.readAsDataURL(file)
    },

    // 上传成功
    async handleSuccess(resp, file) {
      this.uploadLoading = false
      this.isUploading = false
      this.progress = 0
      this.reads(file.raw)
      this.$emit('success', resp)
    },

    // 上传失败
    handleError() {
      this.uploadLoading = false
      this.isUploading = false
      this.progress = 0
      Tip.error('上传图片失败')
    },

    // 上传过程
    handleProgress(e) {
      this.progress = Math.round(e.percent)
    },

    // 左移
    moveLeft(index) {
      if (this.imageList.length <= 1 || index == 0) return
      let list = _.clone(this.imageList)
      ;[list[index], list[index - 1]] = [list[index - 1], list[index]]
      this.imageList = list
      this.emit()
    },

    // 右移
    moveRight(index) {
      if (this.imageList.length <= 1 || index == this.imageList.length - 1)
        return
      let list = _.clone(this.imageList)
      ;[list[index], list[index + 1]] = [list[index + 1], list[index]]
      this.imageList = list
      this.emit()
    },

    // 预览
    preview(index) {
      this.isShowPreview = true
      this.previewImage = this.imageList[index]
    },

    // 删除
    remove(index) {
      this.imageList.splice(index, 1)
      this.emit()
    }
  }
}
